package com.have.blog.admin.service.impl;


import com.have.blog.admin.constant.AdminBlogConstant;
import com.have.blog.admin.constant.AdminMessageConstant;
import com.have.blog.admin.constant.AdminRedisConstant;
import com.have.blog.admin.redis.SystemConfigCacheService;
import com.have.blog.admin.service.SystemConfigService;
import com.have.blog.base.constant.BaseConstant;
import com.have.blog.base.constant.BaseRedisConstant;
import com.have.blog.base.dto.SystemConfigDto;
import com.have.blog.base.enums.BlogOpenStatus;
import com.have.blog.base.enums.BlogStatus;
import com.have.blog.base.enums.FilePriority;
import com.have.blog.base.exception.QueryException;
import com.have.blog.base.wrapper.Wrapper;
import com.have.blog.config.service.RedisService;
import com.have.blog.model.mapper.SystemConfigMapper;
import com.have.blog.model.models.SystemConfig;
import com.have.blog.model.models.SystemConfigExample;
import com.have.blog.utils.MyBeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
@SuppressWarnings("all")
public class SystemConfigServiceImpl implements SystemConfigService {

    @Autowired
    private SystemConfigCacheService systemConfigCacheService;
    @Autowired
    private SystemConfigMapper systemConfigMapper;
    @Autowired
    private RedisService redisService;
    @Value("${redis.admin.database}")
    private String REDIS_KEY_DATABASE;

    @Override
    public SystemConfigDto getConfig() {
        SystemConfig systemConfig = systemConfigCacheService.getSystemConfig();
        if (systemConfig == null) {
            SystemConfigExample example = new SystemConfigExample();
            example.createCriteria()
                    .andStatusEqualTo(BlogStatus.ENABLE.getStatus());
            example.setOrderByClause("create_time desc");
            List<SystemConfig> systemConfigList = systemConfigMapper.selectByExample(example);
            if (CollectionUtils.isEmpty(systemConfigList)) {
                throw new QueryException(AdminMessageConstant.SYSTEM_CONFIG_IS_NOT_EXIST);
            }
            systemConfig = systemConfigList.get(0);
            systemConfigCacheService.setSystemConfig(systemConfig);
        }
        SystemConfigDto systemConfigDto = MyBeanUtils.copyProperties(systemConfig, SystemConfigDto::new);
        return systemConfigDto;
    }

    @Override
    public Wrapper cleanRedisByKey(List<String> keys) {
        if (CollectionUtils.isEmpty(keys)) {
            return Wrapper.failed();
        }
        keys.forEach(key -> {
            if (AdminRedisConstant.ALL.equals(key)) { // 清空redis
                redisService.del(BaseConstant.SYMBOL_STAR);
            } else {
                String delKey = REDIS_KEY_DATABASE + AdminRedisConstant.SEGMENTATION
                        + key+ AdminRedisConstant.SEGMENTATION
                        + AdminRedisConstant.STAR;
                redisService.del(delKey);
            }
        });
        return Wrapper.success();
    }

    @Override
    public Wrapper editSystemConfig(SystemConfigDto systemConfigVO) {
        // 图片必须选择上传到一个区域
        if (BlogOpenStatus.CLOSE.equals(systemConfigVO.getUploadLocal()) && BlogOpenStatus.CLOSE.equals(systemConfigVO.getUploadQiNiu()) && BlogOpenStatus.CLOSE.equals(systemConfigVO.getUploadMinio())) {
            return Wrapper.failed(AdminMessageConstant.PICTURE_MUST_BE_SELECT_AREA);
        }
        // 图片显示优先级为本地优先，必须开启图片上传本地
        if ((FilePriority.LOCAL.equals(systemConfigVO.getPicturePriority())
                || FilePriority.LOCAL.equals(systemConfigVO.getContentPicturePriority()))
                && BlogOpenStatus.CLOSE.equals(systemConfigVO.getUploadLocal())) {
            return Wrapper.failed(AdminMessageConstant.MUST_BE_OPEN_LOCAL_UPLOAD);
        }
        // 图片显示优先级为七牛云优先，必须开启图片上传七牛云
        if ((FilePriority.QI_NIU.equals(systemConfigVO.getPicturePriority())
                || FilePriority.QI_NIU.equals(systemConfigVO.getContentPicturePriority()))
                && BlogOpenStatus.CLOSE.equals(systemConfigVO.getUploadQiNiu())) {
            return Wrapper.failed(AdminMessageConstant.MUST_BE_OPEN_QI_NIU_UPLOAD);
        }
        // 图片显示优先级为Minio优先，必须开启图片上传Minio
        if ((FilePriority.MINIO.equals(systemConfigVO.getPicturePriority())
                ||FilePriority.MINIO.equals(systemConfigVO.getContentPicturePriority()))
                && BlogOpenStatus.CLOSE.equals(systemConfigVO.getUploadMinio())) {
            return Wrapper.failed(AdminMessageConstant.MUST_BE_OPEN_MINIO_UPLOAD);
        }

        // 开启Email邮件通知时，必须保证Email字段不为空
        if (BlogOpenStatus.OPEN.equals(systemConfigVO.getStartEmailNotification()) && StringUtils.isEmpty(systemConfigVO.getEmail())) {
            return Wrapper.failed(AdminMessageConstant.MUST_BE_SET_EMAIL);
        }
        if (StringUtils.isEmpty(systemConfigVO.getUid())) {
            SystemConfig systemConfig = new SystemConfig();
            // 设置七牛云、邮箱、系统配置相关属性【使用Spring工具类提供的深拷贝】
            MyBeanUtils.copyProperties(systemConfigVO, systemConfig, AdminBlogConstant.STATUS, AdminBlogConstant.UID);
            systemConfig.setUpdateTime(new Date());
            systemConfigMapper.insert(systemConfig);
        } else {
            SystemConfig systemConfig = systemConfigMapper.selectByPrimaryKey(systemConfigVO.getUid());

//            // 判断是否更新了图片显示优先级【如果更新了，需要请求Redis中的博客，否者将导致图片无法正常显示】
//            if(systemConfigVO.getPicturePriority() != systemConfig.getPicturePriority()) {
//                blogService.deleteRedisByBlog();
//            }

            MyBeanUtils.copyProperties(systemConfigVO, systemConfig, AdminBlogConstant.STATUS, AdminBlogConstant.UID);
            systemConfigMapper.updateByPrimaryKeySelective(systemConfig);
        }
        // 更新系统配置成功后，需要删除Redis中的系统配置
        systemConfigCacheService.delSystemConfig();
        return Wrapper.successWithMessage(AdminMessageConstant.UPDATE_SUCCESS);
    }
}
